package net.lab1024.sa.admin.module.business.core.material.service;

import java.util.List;
import java.util.stream.Collectors;

import net.lab1024.sa.admin.module.business.core.material.dao.MaterialCategoryDao;
import net.lab1024.sa.admin.module.business.core.material.domain.entity.MaterialCategoryEntity;
import net.lab1024.sa.admin.module.business.core.material.domain.form.MaterialCategoryAddForm;
import net.lab1024.sa.admin.module.business.core.material.domain.form.MaterialCategoryQueryForm;
import net.lab1024.sa.admin.module.business.core.material.domain.form.MaterialCategoryUpdateForm;
import net.lab1024.sa.admin.module.business.core.material.domain.vo.MaterialCategoryTreeVo;
import net.lab1024.sa.admin.module.business.core.material.domain.vo.MaterialCategoryVO;
import net.lab1024.sa.admin.util.RedisIdWorker;
import net.lab1024.sa.base.common.util.SmartBeanUtil;
import net.lab1024.sa.base.common.util.SmartPageUtil;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.domain.PageResult;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;

/**
 * 物料分类表 Service
 *
 * @Author ADog
 * @Date 2025-09-19 19:48:13
 * @Copyright 1.0
 */

@Service
public class MaterialCategoryService {

    @Resource
    private MaterialCategoryDao materialCategoryDao;


    /**
     * 分页查询
     */
    public PageResult<MaterialCategoryVO> queryPage(MaterialCategoryQueryForm queryForm) {
        Page<?> page = SmartPageUtil.convert2PageQuery(queryForm);
        List<MaterialCategoryVO> list = materialCategoryDao.queryPage(page, queryForm);
        return SmartPageUtil.convert2PageResult(page, list);
    }

    /**
     * 添加
     */
    public ResponseDTO<String> add(MaterialCategoryAddForm addForm) {
        MaterialCategoryEntity materialCategoryEntity = SmartBeanUtil.copy(addForm, MaterialCategoryEntity.class);
        materialCategoryDao.insert(materialCategoryEntity);
        //1、如果当前的父ID不为空，代表当前为添加下级
        if (null != addForm.getParentId()){
            // 2、更新父节点的叶子标志
            materialCategoryDao.updateIsLeaf(addForm.getParentId(), 0);
        }
        return ResponseDTO.ok();
    }

    /**
     * 更新
     *
     */
    public ResponseDTO<String> update(MaterialCategoryUpdateForm updateForm) {
        MaterialCategoryEntity materialCategoryEntity = SmartBeanUtil.copy(updateForm, MaterialCategoryEntity.class);
        materialCategoryDao.updateById(materialCategoryEntity);
        return ResponseDTO.ok();
    }

    /**
     * 批量删除
     */
    public ResponseDTO<String> batchDelete(List<Long> idList) {
        if (CollectionUtils.isEmpty(idList)){
            return ResponseDTO.ok();
        }

        materialCategoryDao.deleteBatchIds(idList);
        return ResponseDTO.ok();
    }

    /**
     * 单个删除
     */
    public ResponseDTO<String> delete(Long materialCategoryId) {
        if (null == materialCategoryId){
            return ResponseDTO.ok();
        }

        materialCategoryDao.deleteById(materialCategoryId);
        return ResponseDTO.ok();
    }

    /**
     * 获取树结构
     */
    public List<MaterialCategoryTreeVo> getTree() {
        // 1. 查询所有有效分类（未删除、未禁用）
        List<MaterialCategoryTreeVo> allCategories = materialCategoryDao.selectAllValidCategory();

        // 2. 递归构建树形结构，从顶级节点（parent_id=0）开始
        return treeList(allCategories, 0L);
    }

    /**
     * 递归构造树形结构
     * @param treeList 所有分类列表
     * @param parentId 父级ID，首次调用传入0（顶级节点）
     * @return 以parentId为父级的所有子分类树形结构
     */
    private List<MaterialCategoryTreeVo> treeList(List<MaterialCategoryTreeVo> treeList, Long parentId) {
        // 1. 筛选出当前父级ID下的所有直接子节点
        List<MaterialCategoryTreeVo> children = treeList.stream()
                .filter(category -> parentId.equals(category.getParentId()))
                // 按排序号升序排列，保证显示顺序正确
                .sorted((c1, c2) -> c1.getSortOrder().compareTo(c2.getSortOrder()))
                .collect(Collectors.toList());

        // 2. 递归为每个子节点设置其子节点
        for (MaterialCategoryTreeVo child : children) {
            // 递归查询当前子节点的子节点，形成嵌套结构
            List<MaterialCategoryTreeVo> grandChildren = treeList(treeList, child.getMaterialCategoryId());
            child.setChildren(grandChildren);
        }

        return children;
    }
}
